package com.jn.server;

import org.springframework.util.StringUtils;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.concurrent.Callable;

/**
 * @author 江南大学1033190417
 * @date 2022/4/7 19:52
 */
public class ConnectionThread implements Callable {

    public Socket client;//连接Web浏览器的socket字

    public int counter;//计数器

    public String path;

    public ConnectionThread(Socket cl, int c, String path) {
        this.client = cl;
        this.counter = c;
        this.path = path;
    }

    @Override
    public Object call() throws Exception {
        Result result = new Result();
        String deskIP = client.getInetAddress().toString();//客户机IP地址
        int destport = client.getPort();//客户机端口号
        result.IP = deskIP;
        result.port = destport;
        PrintStream outstream = new PrintStream(client.getOutputStream());
        DataInputStream instream = new DataInputStream(client.getInputStream());
        //读取Web浏览器提交的请求信息
        String inline = instream.readLine();//GET /index.html HTTP/1.1
        if (StringUtils.isEmpty(inline)){
            return result;
        }
        if (getrequest(inline)) {//如果是GET请求
            result.method = "GET";
            String filename = path + getfilename(inline);
            result.file = filename;
            File file = new File(filename);
            if (file.exists()) {
                result.isExist = true;
                //若文件存在，则将文件送给Web浏览器
                outstream.println("HTTP/1.0 200OK");
                outstream.println("mime_version: 1.0");
                outstream.println("Content-Type: text/html;charset=utf-8");
                int len = (int) file.length();
                result.length = len;
                outstream.println("content_length: " + len);
                sendfile(outstream, file);//发送文件
                outstream.close();
            } else {//文件不存在时
                result.isExist = false;
                String notfound = "<html><head><title> Not Found</title></head> <body><h1> Error404-File notfound </h1></body ></html> ";
                outstream.println("HTTP/1.0 404 no found");
                outstream.println("Content-Type: text/html;charset=utf-8");
                outstream.println("Content_Length: " + notfound.length() + 2);
                result.length = notfound.length() + 2;
                outstream.println("");
                outstream.println(notfound);
                outstream.flush();
                outstream.close();
            }
        } else if (postrequest(inline)) {//如果是POST请求
            result.method = "POST";
            outstream.println("HTTP/1.0 200OK");
            outstream.println("MIME_version: 1.0");
            outstream.println("Content-Type: text/html;charset=utf-8");
            String found = "<html><head><title> post </title></head> <body><h1> 您发送了一个post请求 </h1></body ></html> ";
            outstream.println(found);
            outstream.flush();
            outstream.close();
        }
        return result;
    }


    //检查是否是get请求
    boolean getrequest(String s) {
        try {
            if (s.substring(0, 3).equalsIgnoreCase("GET"))
                return true;
        }catch (Exception e){
            return false;
        }
        return false;
    }

    //如果是post请求
    boolean postrequest(String s) {
        try {
            if (s.substring(0, 4).equalsIgnoreCase("POST"))
                return true;
        } catch (Exception e) {
            return false;
        }
        return false;
    }


    //获取要访问的文件名
    String getfilename(String s) {
        String f = s.substring(s.indexOf(" ") + 1);
        f = f.substring(0, f.indexOf(" "));
        try {
            if (f.charAt(0) == '/')
                f = f.substring(1);
        } catch (Exception e) {
            System.out.println("Exception：" + e);
        }

        if (f.equals("")) f = "index.html";

        return f;
    }



    /*把指定文件发送给Web浏览器*/

    void sendfile(PrintStream outs, File file) {
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int len = (int) file.length();
            byte buf[] = new byte[len];
            in.readFully(buf);
            outs.write(buf, 0, len);
            outs.flush();
            in.close();
        } catch (Exception e) {

            System.out.println("Error retrieving file.");

            System.exit(1);

        }

    }

}
